<template>
    <div>
        <nav-bar>
            <template v-slot:left></template>
            <template v-slot:default>创建订单</template>
            <template v-slot:right></template>
        </nav-bar>

        <div class="page">
            <div class="up">
                <van-icon name="success" style="top:18px;left:5px;"/>
                <div class="left">                    
                    <div style="color:var(--color-tint)">{{address.name}} {{address.phone}}</div>
                    <div>{{address.province}} {{address.city}} {{address.county}} {{address.address}}</div>
                </div>
                <div class="right">
                    <van-button round size="mini" color="var(--color-tint)" @click="goTo">更换地址</van-button>   
                </div>
            </div>
            <div class="down">
                <van-divider dashed :style="{ color: 'var(--color-tint)', borderColor: 'var(--color-tint)', padding: '0 16px' }">订单商品列表</van-divider>
                <van-card v-for="(item,index) in cartList"
                :num="item.num"
                :price="item.goods.price+'.00'"
                :desc="item.updated_at"
                :title="item.goods.title"
                :thumb="item.goods.cover_url"
                />
            </div>
            
            <van-divider dashed :style="{ color: 'var(--color-tint)', borderColor: 'var(--color-tint)', padding: '0 16px' }">共计 {{tosum}} 件</van-divider>
            <van-submit-bar :price="total * 100"  button-text="生成订单" @submit="onSubmit" />

            <van-popup 
            v-model:show="showPay" 
            closeable
            position="bottom" 
            :style="{ height: '35%' }" 
            @click="close"
            >

            <van-grid :border="false" :column-num="1">
            <van-grid-item>
                支付宝支付<br>
                <van-image width="150" :src="aliyun" />
            </van-grid-item>
            <!-- <van-grid-item>
                微信支付<br>
                <van-image width="140" :src="wechat" />
            </van-grid-item> -->
            </van-grid>

            </van-popup>
        </div>



    </div>
</template>

<script>
import NavBar from 'components/common/navbar/NavBar';
import {getOders,createOrder,payOrder,payOrderStatus} from 'network/order';
import {Toast} from 'vant';
import {useRouter} from 'vue-router';
import { useStore } from 'vuex';
import {reactive,toRefs,computed,onMounted} from 'vue';

export default {
  name:"Addorder",
    components:{
        NavBar
    },
  setup() {
    const router = useRouter();
    const store = useStore();
    const state = reactive({
        cartList:[],
        address:{},
        showPay:false,
        orderNo:'',
        aliyun:'',
        wechat:'',
    });

    
     onMounted(()=>{
         getOders().then(res=>{
        // console.log(res);
        let address = res.address.filter(n=>n.is_default == '1');
        state.address = address[0];
        if (address.length == 0){
            state.address ={
                address:"您还没有添加收货地址",      
            }
            setTimeout(()=>{
                    router.push({path:'/address'})
                },1000)
        }
        let cartList = res.carts;
        state.cartList = cartList;
        //检测是否已经生成过订单，如果是反回购物车
        console.log(cartList.length);
        if(cartList.length === 0){
            Toast('此订单已经提交');
            setTimeout(() => {
                router.push({path:'/car'})
            }, 3000);
        }
       
       })
        
    })

    //跳转
    const goTo =() => {
      router.push({path:'/address'});
    }

    //总价
    const total = computed(()=>{
        let sum = 0;
        state.cartList.forEach(item=>{
            sum += parseInt(item.num) * parseFloat(item.goods.price);
        })
        return sum;
    })

    //总数
    const tosum = computed(()=>{
        let zs = 0;
        state.cartList.forEach(item=>{
            zs += parseInt(item.num);
        })
        return zs;
    })

    
   
            
    
    //创建订单
    const onSubmit = () => {
        const params ={
            address_id:state.address.id
        }

        createOrder(params).then(res=>{
            Toast('创建订单完成');
            store.dispatch('updateCart');
            state.showPay = true;
            //订单ID
            state.orderNo = res.id;

            payOrder(state.orderNo,{type:'aliyun'}).then(res=>{
                console.log(res);
                state.aliyun = res.qr_code_url;
            })
            // payOrder(state.orderNo,{type:'wechat'}).then(res=>{
            //     console.log(res);
            //     state.wechat = res.qr_code_url;
            // })

            //轮询查看 支付状态
            const timer = setInterval(()=>{
                payOrderStatus(state.orderNo).then(res=>{
                    if(res=='2'){                           //支付成功为2，因调不了沙箱支付，所以改成1
                        clearInterval(timer);
                        router.push({path:'/orderdetail',query:{id:state.orderNo}})
                    }
                })
            },3000)

        })
        
    }

    const close =()=>{
        router.push({path:'/orderdetail',query:{id:state.orderNo}})
    }

    return {
        ...toRefs(state),
        goTo,
        onSubmit,
        total,
        tosum,
        close

    }
  },
}
</script>

<style scoped lang="scss">
.page{
    margin-top: 45px;
}
.up{
    display: flex;
    height: 100px;
    .left{
        flex: 1;
        text-align: left;
        padding: 10px;
        line-height: 32px;
    }
    .right{
        margin-top: 10px;
        position: absolute;
        flex:1;
        width: 60px;
        height: 100px;
        right: 10px;
        
    }
}
.down{
    text-align: left;

}
.van-submit-bar{
  bottom: 53px;
}
</style>


